package com.example.wiki.service;

import com.example.wiki.domain.Category;
import com.example.wiki.domain.CategoryExample;
import com.example.wiki.mapper.CategoryMapper;
import com.example.wiki.req.CategoryReq;
import com.example.wiki.req.CategorySaveReq;
import com.example.wiki.resp.CategoryResp;
import com.example.wiki.resp.PageResp;
import com.example.wiki.util.CopyUtil;
import com.example.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;


@Service
public class CategoryService {
    private static final Logger Log = LoggerFactory.getLogger(CategoryService.class);
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private CategoryMapper categoryMapper;

    public PageResp<CategoryResp> list(CategoryReq req){

        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        // 分页

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);

        Log.info("总数目:{}",pageInfo.getTotal());
        Log.info("总页数:{}",pageInfo.getPages());

        List<CategoryResp> categoryRespList = CopyUtil.copyList(categoryList, CategoryResp.class);
        PageResp<CategoryResp> PageResp = new PageResp<>();
        PageResp.setTotal(pageInfo.getTotal());
        PageResp.setList(categoryRespList);
        return PageResp;
    }
    public void save(CategorySaveReq e){
        try{
            Category category = CopyUtil.copy(e,Category.class);
            if(ObjectUtils.isEmpty(e.getId())){
                category.setId(snowFlake.nextId());
                categoryMapper.insert(category);
            } else {
                categoryMapper.updateByPrimaryKey(category);
            }

        }catch (Exception exception){
            exception.printStackTrace();

        }

    }
    public int del(Long id){
        int i = categoryMapper.deleteByPrimaryKey(id);
        return i;
    }
    /**
     * 查询所有数据
     */
    public List<CategoryResp> all(CategoryReq req){

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);



        List<CategoryResp> categoryRespList = CopyUtil.copyList(categoryList, CategoryResp.class);

        return categoryRespList;
    }
}
